using System;
using System.IO;
using System.Text.Json;

namespace TangCaptureTraffic.Services
{
    /// <summary>
    /// 配置服务实现类，负责配置的加载、保存和管理
    /// </summary>
    public class ConfigurationService : IConfigurationService
    {
        private readonly string _configFilePath;
        private Config _currentConfig;

        public ConfigurationService(string configFilePath = "config.json")
        {
            _configFilePath = configFilePath;
            _currentConfig = new Config
            {
                MemoryConfig = new MemoryConfigData()
            };
        }

        /// <summary>
        /// 加载配置
        /// </summary>
        public void LoadConfiguration()
        {
            if (File.Exists(_configFilePath))
            {
                try
                {
                    string json = File.ReadAllText(_configFilePath);
                    var config = JsonSerializer.Deserialize<Config>(json);
                    if (config?.MemoryConfig != null)
                    {
                        _currentConfig = config;
                        ApplyConfigurationToStaticClass();
                        System.Diagnostics.Debug.WriteLine("配置加载成功");
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"加载配置失败: {ex.Message}");
                    // 使用默认配置
                    ApplyConfigurationToStaticClass();
                }
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("配置文件不存在，使用默认配置");
                ApplyConfigurationToStaticClass();
                // 首次运行时保存默认配置
                SaveConfiguration();
            }
        }

        /// <summary>
        /// 保存配置
        /// </summary>
        public void SaveConfiguration()
        {
            try
            {
                // 从静态类同步最新配置
                SyncConfigurationFromStaticClass();
                
                string json = JsonSerializer.Serialize(_currentConfig, new JsonSerializerOptions
                {
                    WriteIndented = true
                });
                File.WriteAllText(_configFilePath, json);
                System.Diagnostics.Debug.WriteLine("配置保存成功");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"保存配置失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 将配置应用到静态类（为了向后兼容）
        /// </summary>
        private void ApplyConfigurationToStaticClass()
        {
            var memoryConfig = _currentConfig.MemoryConfig;
            MemoryConfig.EnableAutoMemoryCleanup = memoryConfig.EnableAutoMemoryCleanup;
            MemoryConfig.MemoryCleanupInterval = memoryConfig.MemoryCleanupInterval;
            MemoryConfig.MaxSessions = memoryConfig.MaxSessions;
            MemoryConfig.SessionCleanupCount = memoryConfig.SessionCleanupCount;
            MemoryConfig.MaxUISessions = memoryConfig.MaxUISessions;
            MemoryConfig.UISessionCleanupCount = memoryConfig.UISessionCleanupCount;
            MemoryConfig.MemoryWarningThreshold = memoryConfig.MemoryWarningThreshold;
        }

        /// <summary>
        /// 从静态类同步配置（为了向后兼容）
        /// </summary>
        private void SyncConfigurationFromStaticClass()
        {
            _currentConfig.MemoryConfig.EnableAutoMemoryCleanup = MemoryConfig.EnableAutoMemoryCleanup;
            _currentConfig.MemoryConfig.MemoryCleanupInterval = MemoryConfig.MemoryCleanupInterval;
            _currentConfig.MemoryConfig.MaxSessions = MemoryConfig.MaxSessions;
            _currentConfig.MemoryConfig.SessionCleanupCount = MemoryConfig.SessionCleanupCount;
            _currentConfig.MemoryConfig.MaxUISessions = MemoryConfig.MaxUISessions;
            _currentConfig.MemoryConfig.UISessionCleanupCount = MemoryConfig.UISessionCleanupCount;
            _currentConfig.MemoryConfig.MemoryWarningThreshold = MemoryConfig.MemoryWarningThreshold;
        }

        /// <summary>
        /// 获取最大会话数量
        /// </summary>
        public int GetMaxSessions() => _currentConfig.MemoryConfig.MaxSessions;

        /// <summary>
        /// 获取会话清理数量
        /// </summary>
        public int GetSessionCleanupCount() => _currentConfig.MemoryConfig.SessionCleanupCount;

        /// <summary>
        /// 获取UI最大会话数量
        /// </summary>
        public int GetMaxUISessions() => _currentConfig.MemoryConfig.MaxUISessions;

        /// <summary>
        /// 获取UI会话清理数量
        /// </summary>
        public int GetUISessionCleanupCount() => _currentConfig.MemoryConfig.UISessionCleanupCount;

        /// <summary>
        /// 获取内存清理间隔
        /// </summary>
        public int GetMemoryCleanupInterval() => _currentConfig.MemoryConfig.MemoryCleanupInterval;

        /// <summary>
        /// 是否启用自动内存清理
        /// </summary>
        public bool IsAutoMemoryCleanupEnabled() => _currentConfig.MemoryConfig.EnableAutoMemoryCleanup;

        /// <summary>
        /// 获取内存警告阈值
        /// </summary>
        public int GetMemoryWarningThreshold() => _currentConfig.MemoryConfig.MemoryWarningThreshold;

        /// <summary>
        /// 更新内存配置
        /// </summary>
        /// <param name="config">内存配置数据</param>
        public void UpdateMemoryConfiguration(MemoryConfigData config)
        {
            if (config == null) throw new ArgumentNullException(nameof(config));
            
            _currentConfig.MemoryConfig = config;
            ApplyConfigurationToStaticClass();
            SaveConfiguration();
        }
    }
}